﻿var mydata;
var search;
var searchString = "";
var resetSearch;
var graduateSearch;
var NograduateSearch;

layui.use(['table', 'layer', 'jquery', 'form', 'layer'],
    function () {
        var table = layui.table;
        var $ = layui.jquery;
        var form = layui.form;
        var layer = layui.layer;

        function studyYearRender(data) {
            // 页面渲染
            data.forEach(r => {
                $('[name="studyYear"]').append(`<option value="${r.ID}">${r.Name}</option>`);
            });
            // 重新渲染表单
            form.render();
            
        }

        if (SessionStorageHaveInfo("studyYear")) {
            studyYearRender(JSON.parse(SessionStorageHaveInfo("studyYear")));
        } else {
            //请求学年数据
            $.get('/api/getstudyyaarsinfo',
                function (res) {
                    //放入sessionstorage
                    sessionStorage.setItem("studyYear", JSON.stringify(res));
                    //渲染
                    studyYearRender(res);

                });
        }
        
        $('#search').val(searchString);

        search = function () {
            searchString = $('#search').val();
            tableIns.reload({
                where: { search: searchString }
            });
            $('#search').val(searchString);
        }

        resetSearch = function () {
            searchString = "";
            tableIns.reload({
                where: { search: "" }
            });
            $('#search').val(searchString);
        }
        //毕业班级查询
        graduateSearch = function () {
            tableIns.reload({
                where: { search: "", isGraduate: 1 }
            });
            $("#noGraduate").css('display', 'block');
            $("#graduate").css('display', 'none');
            $("#search").attr("placeholder", "请输入已毕业班级编号查询");
        }

        //未毕业班级查询
        NograduateSearch = function () {
            tableIns.reload({
                where: { search: "", isGraduate: 2 }
            });
            $("#noGraduate").css('display', 'none');
            $("#graduate").css('display', 'block');
            $("#search").attr("placeholder", "请输入未毕业班级编号查询");
        }

        $('#into').click(function () {
            if ($("[name='studyYear']").val() =='') {
                layer.msg("请选择学年", { icon: 2 });
                return;
            }
            $('#select').css('display', 'none');
            $('#content').css('display', 'block');
            //请求数据
            
            $('#tcTitle').text($('#tcTitle').text().slice(0,7) + '--' + $("#opt option:selected").text());
            sessionStorage.setItem("syId", $("#opt").val());

            //渲染已有课程
            tableRender();
            loadCourseSelect();
            
        });

        function tableRender() {
            //渲染已有课程
            table.render({
                elem: '#text', //指定原始表格元素选择器（推荐id选择器）
                url: '/api/getclass_course',
                where: {
                    cid: sessionStorage.getItem("classId"),
                    syId: sessionStorage.getItem("syId")
                },
                height: 315, //容器高度
                cols: [[ //表头
                    { type:"numbers", title: '序号', width: 80, fixed: 'left' },
                    { field: 'courseName', title: '课程名称', width: 180 },
                    { field:"teacherName",title:"任课教师"}
                ]]
            });
        }

        /**
         * 加载课程选择下拉框
         */
        function loadCourseSelect() {
            var index = layer.load();
            // 加载课程下拉框
            $.get('/api/course/classhavenocourse',
                {
                    classId: sessionStorage.getItem("classId"),
                    studyYear: sessionStorage.getItem("syId")
                },
                function (res) {
                    let sel = $('[name="course"]');
                    sel.empty();
                    sel.append('<option value="">输入或选择课程</option>');
                    res.forEach(r => sel.append(`<option value="${r.id}">${r.name}</option>`));
                    form.render();
                    layer.close(index);
                });
        }

        $('#inout').click(function () {
            $('#select').css('display', 'block'); 
            $('#content').css('display', 'none');
            //清空
            $('[name="course"]').empty();
            $('[name="teacher"]').empty();
            form.render();
        });

        form.on('select(course)',
            function (data) {
                var index = layer.load();
                $.get("/api/course/getcourseteachers",
                    { courseId: data.value },
                    function(res) {
                        let sel = $('[name="teacher"]');
                        sel.empty();
                        sel.append('<option value="">输入或选择教师</option>');
                        res.forEach(r => sel.append(`<option value="${r.id}">${r.name}</option>`));
                        form.render();
                        layer.close(index);
                    });
            });

        // 监听添加按钮
        $('#addcourse').click(function() {
            let param = {
                classId: sessionStorage.getItem("classId"),
                studyYear: sessionStorage.getItem("syId"),
                courseId: $('[name="course"]').val(),
                teacherId: $('[name="teacher"]').val()
            };
           
            form.render();
            $.post("/api/course/classaddcourse",
                param,
                function(res) {
                    if (res) {
                        layer.msg("添加成功", { icon: 1 });
                        // TODO:刷新已有课程表
                        // 清除下拉框
                        $(`select[name='course'] option[value='${param.courseId}']`).remove();
                        $('[name="teacher"]').empty();
                        tableRender();
                    } else {
                        layer.msg("添加失败!", { icon: 2 });
                    }
                });
        });


        let tableOptions = {
            elem: '#mytable',
            height: 650,
            url: "/api/getallclass_",
            where: { search: "", isGraduate: 0 },
            page: true, //开启分页
            defaultToolbar: ['print'],
            limit: 12,
            toolbar: '#mytoolbar',
            cols: [
                [//表头
                    { type: 'checkbox', fixed: 'left', width: 60 },
                    { type: 'numbers', width: 88 },
                    { field: 'id', title: 'ID', width: 80, fixed: 'left', hide: true, align: 'center' },
                    { field: 'classCode', title: '班级编号', width: 200, align: 'center' },
                    { field: 'grade', title: '年级', width: 190, align: 'center' },
                    { field: 'major', title: '专业名称', width: 182, align: 'center' },
                    { field: 'isGraduate', title: '班级状态', width: 182, align: 'center' },
                    { toolbar: '#mybar', title: '操作', width: 300, align: 'center' },
                ]
            ]
        }

        //大表实例
        var tableIns = table.render(tableOptions);


        //监听工具栏事件
        table.on('toolbar(test)',
            function(obj) {
                switch (obj.event) {
                case 'add':
                    layer.msg('添加');
                    openAddUser();
                    break;
                }
            });

        var url;
        var mainIndex;
        //打开添加页面
        function openAddUser() {
            mainIndex = layer.open({
                type: '1',
                title: '添加用户',
                content: $("#saveOrUpdateDiv"),
                area: ['380px', '350px'],
                success: function (index) {
                    url = "user/addUser.action";
                }
            });
        }

        //提交
        form.on("submit(doSubmit)",
            function(obj) {
                //序列化表单数据
                var params = $("#dataFrm").serialize();
                alert(params);
                $.post("/api/insertclass_",
                    params,
                    function(obj) {
                        layer.msg("成功", {icon:1});
                        //关闭弹出层
                        layer.close(mainIndex);
                        //刷新数据表格
                        layer.reload(tableIns);
                    });
            });

        //监听行工具事件
        table.on('tool(test)',
            function (obj) {
                var data = obj.data;
                //console.log(obj)
                var layEvent = obj.event;
                if (layEvent === 'del') {
                    layer.confirm('真的删除行么',
                        function (index) {
                            obj.del();
                            layer.close(index);


                        });
                }
                else if (layEvent === 'edit') {
                    layer.open({
                        type: '1',
                        title: '教学安排',
                        success: function() {
                            $('#tcTitle').text(data.classCode);
                            sessionStorage.setItem("classId",data.id);
                        },
                        content: $("#tc"),
                        area: ["440px", "400px"],
                        end: function() {
                            // location.reload();
                            $('#select').css('display', 'block');
                            $('#content').css('display', 'none');
                            $('[name="course"]').empty();
                            $('[name="teacher"]').empty();
                            form.render();
                        }
                    });
                }
            });

    });